package com.canbot.u05.activity.presidemode.newcode;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.widget.ImageButton;

import com.canbot.u05.R;
import com.canbot.u05.activity.presidemode.newcode.adapter.NHostTaskAddAdapter;
import com.canbot.u05.activity.presidemode.newcode.bean.ActionBean;
import com.canbot.u05.activity.presidemode.newcode.bean.DanceBean;
import com.canbot.u05.activity.presidemode.newcode.bean.HostItemBean;
import com.canbot.u05.activity.presidemode.newcode.bean.HostModuleData;
import com.canbot.u05.activity.presidemode.newcode.bean.ModuleUtil;
import com.canbot.u05.activity.presidemode.newcode.bean.MoveBean;
import com.canbot.u05.activity.presidemode.newcode.bean.NModuleType;
import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil;
import com.canbot.u05.activity.presidemode.newcode.bean.PicturnEmotionBean;
import com.canbot.u05.activity.presidemode.newcode.bean.VoiceBean;
import com.canbot.u05.activity.presidemode.newcode.interfaces.IDialogBtnLisenter;
import com.canbot.u05.activity.presidemode.newcode.interfaces.IResponse;
import com.canbot.u05.activity.presidemode.newcode.interfaces.ITaskItemClick;
import com.canbot.u05.activity.presidemode.newcode.view.NHostBaseDialog;
import com.canbot.u05.activity.presidemode.newcode.view.NHostEditnameDialog;
import com.canbot.u05.activity.presidemode.newcode.view.NHostExitDialog;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NhostTaskAddActivity extends BaseHostActivity {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.delete)
    ImageButton delete;
    private NHostTaskAddAdapter nHostTaskAddAdapter;
    private List<HostItemBean> hostItemBeanList;
    private HostModuleData hostModuleData;
    private ItemTouchHelper itemTouchHelper;
    private int selectPos = 0;
    private HostItemBean currenItemData;
    private NHostBaseDialog nHostBaseDialog;
    private boolean isNewAdd;

    @OnClick(R.id.close)
    public void close() {
        nHostBaseDialog = new NHostExitDialog(this, NHostExitDialog.CLOSE);
        nHostBaseDialog.setiDialogBtnLisenter(result -> {
            finish();
        });
        nHostBaseDialog.show();
    }

    @Override
    public void onBackPressed() {
        close();
    }

    @OnClick(R.id.save)
    public void save() {
        boolean haveEmpty = false;
        for (HostItemBean hostItemBean : hostItemBeanList) {
            if (ModuleUtil.checkEmpty(hostItemBean)) {
                haveEmpty = true;
                break;
            }
        }
        if (haveEmpty) {
            nHostBaseDialog = new NHostExitDialog(this, NHostExitDialog.SAVE);
            nHostBaseDialog.setiDialogBtnLisenter(result -> {
                emptyHandler();
            });
            nHostBaseDialog.show();
        } else {
            checkData();
        }
    }

    private void emptyHandler() {
        Iterator<HostItemBean> iterator = hostItemBeanList.iterator();
        while (iterator.hasNext()) {
            HostItemBean hostItemBean = iterator.next();
            if (hostItemBean != null) {
                if (ModuleUtil.checkEmpty(hostItemBean)) {
                    iterator.remove();
                }
            }
        }
        nHostTaskAddAdapter.notifyDataSetChanged();
        checkData();
    }

    private void checkData() {
        if (hostModuleData != null && hostItemBeanList.size() > 0) {
            hostModuleData.setTaskNodes(hostItemBeanList);
            updateServerData();
        } else {
            if (hostItemBeanList.size() == 0) {
                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.module_content_is_null));
            } else {
                nHostBaseDialog = new NHostEditnameDialog(this, NHostEditnameDialog.EDITNAME);
                nHostBaseDialog.setiDialogBtnLisenter((IDialogBtnLisenter<String>) result -> {
                    if (ModuleUtil.checkNameExist(result.trim(), NHostTaskListActivity.listData)) {
                        ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.task_name_exist));
                    } else {
                        hostModuleData = new HostModuleData();
                        hostModuleData.setTaskName(result);
                        checkData();
                    }
                });
                nHostBaseDialog.show();
            }
        }
    }

    private void updateServerData() {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        IResponse<String> iResponse = new IResponse<String>() {
            @Override
            public void onSucusse(String result) {
                LoadingDialogUtils.closeDialog(dialogLoading);
                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.upload_complete));
                Intent intent = new Intent();
                intent.putExtra(DATA, hostModuleData);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onFailuer(String result) {
                ToastTools.newInstance(getApplicationContext()).showText(result);
                LoadingDialogUtils.closeDialog(dialogLoading);
            }
        };
        if (isNewAdd) {
            NetLoadUtil.addTaskData(this, iResponse, hostModuleData);
        } else {
            NetLoadUtil.updateTaskData(this, iResponse, hostModuleData);
        }
    }

    @OnClick(R.id.btn_add_normal)
    public void addNormal() {
        hostItemBeanList.add(new HostItemBean(HostItemBean.ITEM_TYPE_NORMAL));
        notifyDataAdd(nHostTaskAddAdapter.getItemCount() - 1);
    }

    private void notifyDataAdd(int i) {
        nHostTaskAddAdapter.notifyItemInserted(i);
        recycleView.scrollToPosition(nHostTaskAddAdapter.getItemCount() - 1);
    }

    @OnClick(R.id.btn_add_dance)
    public void addDance() {
        gotoActivityForResult(NChoiceDanceActivity.class,
                NModuleType.DANCE_ADD, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initEventData() {
        EventBus.getDefault().register(this);
        MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(19));
        recycleView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        ((SimpleItemAnimator) recycleView.getItemAnimator()).setSupportsChangeAnimations(false);
        hostItemBeanList = mockData();
        nHostTaskAddAdapter = new NHostTaskAddAdapter(hostItemBeanList, this, new ITaskItemClick() {
            @Override
            public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
                itemTouchHelper.startDrag(viewHolder);
            }

            @Override
            public void onPauseOrPlay(int pos) {
                pauseOrPlay(pos);
            }

            @Override
            public void onVoiceChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NVoiceChoiceSettingsActivity.class,
                        NModuleType.VOICE, hostItemBeanList.get(pos).getVoiceBean());
            }

            @Override
            public void onActionChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NActionChoiceSettingsActivity.class,
                        NModuleType.ACTION, (Serializable) hostItemBeanList.get(pos).getActionBeanList());
            }

            @Override
            public void onMoveChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NMoveChoiceActivity.class,
                        NModuleType.MOVE, hostItemBeanList.get(pos).getMoveBean());
            }

            @Override
            public void onPictureChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NPictureChoiceSettingActivity.class,
                        NModuleType.PICTURE_EMOTION, hostItemBeanList.get(pos).getPicturnEmotionBean());
            }

            @Override
            public void onDanceActionChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NChoiceDanceActivity.class,
                        NModuleType.DANCE_EDIT, hostItemBeanList.get(pos).getDanceBean());
            }

            @Override
            public void onDanceMusicChoice(int pos) {
                selectPos = pos;
                gotoActivityForResult(NChoiceMusicActivity.class,
                        NModuleType.DANCE_MUSIC, hostItemBeanList.get(pos).getVoiceBean());
            }
        });
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            private boolean isDelete;
            private RecyclerView.ViewHolder mViewHolder;

            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                int fromPos = viewHolder.getAdapterPosition();
                int toPos = target.getAdapterPosition();
                Collections.swap(hostItemBeanList, fromPos, toPos);
                nHostTaskAddAdapter.notifyItemMoved(fromPos, toPos);
                return true;
            }

            @Override
            public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
                //拖拽的时候
                if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
                    isDelete = true;
                    int width = delete.getWidth();
                    int height = delete.getHeight();
                    int[] ints = new int[2];
                    int[] ints2 = new int[2];
                    delete.getLocationOnScreen(ints);
                    int w = mViewHolder.itemView.getWidth();
                    int h = mViewHolder.itemView.getHeight();
                    mViewHolder.itemView.getLocationOnScreen(ints2);
                    Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w, ints2[1] + h);
                    boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                    if (contains) {
                        int adapterPosition = mViewHolder.getAdapterPosition();
                        hostItemBeanList.remove(adapterPosition);
                        itemTouchHelper.onChildViewDetachedFromWindow(mViewHolder.itemView);
                        nHostTaskAddAdapter.notifyItemRemoved(adapterPosition);
                    } else {
                        isDelete = false;
                    }
                } else {
                    isDelete = false;
                    mViewHolder = viewHolder;
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

            }

            /**
             * 长按拖长按拖拽删除 true  自己处理 false 调用 itemTouchHelper.startDrag(holder);
             */
            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            /**
             * 滑动删除
             *
             * @return
             */
            @Override
            public boolean isItemViewSwipeEnabled() {
                return false;
            }

            @Override
            public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                if (isDelete) {
                    return;
                }
                updateDragInfo(viewHolder, actionState);
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            @Override
            public void onChildDrawOver(@NonNull Canvas c, @NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                if (isDelete) {
                    return;
                }
                updateDragInfo(viewHolder, actionState);
                super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                recyclerView.post(() -> {
                    delete.setSelected(false);
                    nHostTaskAddAdapter.notifyDataSetChanged();
                });
            }
        });
        itemTouchHelper.attachToRecyclerView(recycleView);
        recycleView.setAdapter(nHostTaskAddAdapter);
    }

    private Dialog dialogLoading;

    private void pauseOrPlay(int pos) {
        HostItemBean hostItemBean = hostItemBeanList.get(pos);
        if (currenItemData != null && currenItemData != hostItemBean && currenItemData.isPlay()) {
            currenItemData.setPlay(false);
        }
        if (ModuleUtil.checkEmpty(hostItemBean)) {
            ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.module_content_is_null));
        } else {
            boolean play = hostItemBean.isPlay();
            dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
            NetLoadUtil.playTaskOrStop(getApplicationContext(), new IResponse<String>() {
                @Override
                public void onSucusse(String result) {
                    LoadingDialogUtils.closeDialog(dialogLoading);
                    hostItemBean.setPlay(!play);
                    currenItemData = hostItemBean;
                    runOnUiThread(() -> nHostTaskAddAdapter.notifyDataSetChanged());
                }

                @Override
                public void onFailuer(String result) {
                    LoadingDialogUtils.closeDialog(dialogLoading);
                    ToastTools.newInstance(getApplicationContext()).showText(result);
                }
            }, !play, hostItemBean);
        }
    }

    private void updateDragInfo(@NonNull RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            int width = delete.getWidth();
            int height = delete.getHeight();
            int[] delelteViewPos = new int[2];
            int[] itemViewPos = new int[2];
            delete.getLocationOnScreen(delelteViewPos);
            int w = viewHolder.itemView.getWidth();
            int h = viewHolder.itemView.getHeight();
            viewHolder.itemView.getLocationOnScreen(itemViewPos);
            Rect rect = new Rect(itemViewPos[0], itemViewPos[1], itemViewPos[0] + w, itemViewPos[1] + h);
            boolean contains = rect.contains(delelteViewPos[0] + width / 2, delelteViewPos[1] + height / 2);
            delete.setSelected(contains);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMapEvent(StringMsgBean bean) {
        switch (bean.getMsgType()) {
            case MsgType.COMPERE_RAN_TASK_END:
                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.task_compeled));
                if (currenItemData != null && currenItemData.isPlay()) {
                    currenItemData.setPlay(false);
                    nHostTaskAddAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    private List<HostItemBean> mockData() {
        List<HostItemBean> hostItemBeans = new ArrayList<>();
        hostModuleData = (HostModuleData) getIntent().getSerializableExtra(DATA);
        if (hostModuleData != null) {
            hostItemBeans = hostModuleData.getTaskNodes();
            isNewAdd = false;
        } else {
            isNewAdd = true;
        }
        return hostItemBeans;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_nhost_task_add;
    }

    private static final String TAG = "NhostTaskAddActivity";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (intent != null) {
            switch (requestCode) {
                case NModuleType.DANCE_ADD:
                    DanceBean danceBean = (DanceBean) intent.getSerializableExtra(DATA);
                    HostItemBean hostItemBean = new HostItemBean(HostItemBean.ITEM_TYPE_DANCE);
                    hostItemBean.setDanceBean(danceBean);
                    hostItemBeanList.add(hostItemBean);
                    nHostTaskAddAdapter.notifyItemInserted(hostItemBeanList.size() - 1);
                    recycleView.scrollToPosition(nHostTaskAddAdapter.getItemCount() - 1);
                    break;
                case NModuleType.DANCE_EDIT:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    danceBean = (DanceBean) intent.getSerializableExtra(DATA);
                    hostItemBean.setDanceBean(danceBean);
                    nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    recycleView.scrollToPosition(nHostTaskAddAdapter.getItemCount() - 1);
                    break;
                case NModuleType.DANCE_MUSIC:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    VoiceBean voiceBean = (VoiceBean) intent.getSerializableExtra(DATA);
                    danceBean = hostItemBean.getDanceBean();
                    if (danceBean != null) {
                        danceBean.setType(NModuleType.DANCE_MUSIC);
                        danceBean.setPath(voiceBean.path);
                        if (danceBean.isStandardAudio()) {
                            danceBean.setTime(danceBean.getStandardActionTime());
                        } else {
                            danceBean.setTime(Math.max(voiceBean.time, danceBean.getStandardActionTime()));
                        }
                        nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    }
                    break;
                case NModuleType.MOVE:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    MoveBean moveBean = (MoveBean) intent.getSerializableExtra(DATA);
                    hostItemBean.setMoveBean(moveBean);
                    nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    break;
                case NModuleType.PICTURE_EMOTION:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    if (resultCode == NModuleType.EMOTION || resultCode == NModuleType.PICTURE || resultCode == NModuleType.PICTURE_NONE) {
                        PicturnEmotionBean emotionBean = (PicturnEmotionBean) intent.getSerializableExtra(DATA);
                        hostItemBean.setPicturnEmotionBean(emotionBean);
                        nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    }
                    break;
                case NModuleType.ACTION:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    if (resultCode == NModuleType.ACTION_EXIST) {
                        List<ActionBean> actionBeanList = (List<ActionBean>) intent.getSerializableExtra(DATA);
                        hostItemBean.setActionBeanList(actionBeanList);
                    } else if (resultCode == NModuleType.ACTION_RANDOM) {
                        ActionBean actionBean = (ActionBean) intent.getSerializableExtra(DATA);
                        hostItemBean.setActionBean(actionBean);
                    } else if (resultCode == NModuleType.ACTION_NONE) {
                        ActionBean actionBean = new ActionBean();
                        actionBean.actionType = NModuleType.ACTION_NONE;
                        hostItemBean.setActionBean(actionBean);
                    }
                    nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    break;
                case NModuleType.VOICE:
                    hostItemBean = hostItemBeanList.get(selectPos);
                    voiceBean = (VoiceBean) intent.getSerializableExtra(DATA);
                    hostItemBean.setVoiceBean(voiceBean);
                    nHostTaskAddAdapter.notifyItemChanged(selectPos);
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nHostTaskAddAdapter != null) {
            nHostTaskAddAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (currenItemData != null && currenItemData.isPlay()) {
            currenItemData.setPlay(false);
        }
        MapVoiceAndEyes.stop();
        NetLoadUtil.stop(getApplicationContext());
        LoadingDialogUtils.closeDialog(dialogLoading);
    }
}
